package edu.zjut.sjq.service;

import edu.zjut.sjq.bean.Apply;
import edu.zjut.sjq.bean.Result;
import edu.zjut.sjq.bean.User;
import edu.zjut.sjq.mapper.ApplyMapper;
import edu.zjut.sjq.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by sue on 2017/3/18.
 */
@Service
public class ApplyService {
    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpSession session;

    // 申请成为评分者
    public Result updateRole(Apply apply){
        Result result=new Result();
        result.setRes(0);
        User user = userMapper.selectById(apply.getUserId());
        if (user.getSchoolName()==null || user.getActualName()==null || user.getMajorName()==null
                || user.getPhone()==null){
            result.setMsg("请先完善你的个人真实信息");
            return result;
        }
        apply.setCreateTime(new Date());
        apply.setResult(0);
        Integer res = applyMapper.insert(apply);
        result.setRes(res);
        if (res==1)
            result.setMsg("申请成功,等待审批中...");
        else
            result.setMsg("申请失败");

        return result;
    }

    // 获取所有未处理申请信息
    public List<Apply> getAllApply(){
        // result=0:未处理信息
        return applyMapper.getList(0);
    }

    public Apply selectById(Integer applyId){
        return applyMapper.selectById(applyId);
    }

    // 审批申请
    public Result reviewApply(Apply apply){
        Result result=new Result();
        result.setRes(0);
        if (apply.getId()==null || apply.getResult()==null || apply.getUserId()==null){
            result.setMsg("数据不完整");
            return result;
        }
        User user = (User) session.getAttribute("user");
        if (user!=null){
            apply.setHandUserId(user.getId());
        }
        // 更改审批状态
        Integer reviewRes = applyMapper.review(apply);
        if (reviewRes==1 ){
            if (apply.getResult()==2){
                // 更改身份
                User newUser=new User();
                newUser.setId(apply.getUserId());
                newUser.setRole(apply.getRole());
                Integer updateRes = userMapper.updateInfo(newUser);
                if (updateRes==1){
                    result.setRes(1);
                    result.setMsg("审核成功：通过审核");
                }else
                    result.setMsg("审核失败");
            }else {
                result.setRes(1);
                result.setMsg("审核成功：不通过审核");
            }

        }else
            result.setMsg("审核失败");
        return result;
    }
}
